package com.baizhi.controller;

import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import com.baizhi.util.ImageCodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;

@Controller
@RequestMapping("Admin")
public class AdminController {
    @Resource
    AdminService adminService;

    @Resource
    HttpSession session;

    //登录
    @RequestMapping("login")
    @ResponseBody
    public HashMap<String,Object> login(Admin admin , String clientCode){
        return adminService.login(admin,clientCode);
    }

    //验证码
    @RequestMapping("createCode")
    public void createCode(HttpServletResponse response){
        // 使用工具类获取验证码对象
        String code = ImageCodeUtil.getSecurityCode();
        //3.根据随机验证码创建图片
        BufferedImage image = ImageCodeUtil.createImage(code);
        try {
            ImageIO.write(image,"png",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 获取session
        session.setAttribute("serverCode", code);
    }

    //管理员信息
    @RequestMapping("pageAllAdmin")
    @ResponseBody
    public HashMap<String,Object> pageAllAdmin(Integer page,Integer rows){
        return adminService.pageAllAdmin(page, rows);
    }

    //edit
    @RequestMapping("edit")
    @ResponseBody
    public void edit(Admin admin,String oper){
        if(oper.equals("edit")){
            adminService.update(admin);
        }
        if(oper.equals("del")){
            adminService.del(admin);
        }
        if(oper.equals("add")){
            adminService.add(admin);

        }
    }

    //退出登录
    @RequestMapping("quit")
    public String quit(){
        session.removeAttribute("admin");
        return "redirect:/login/login.jsp";
    }

}
